<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>躁动的小球</title>
    <style>
        #ball {
            position: fixed;
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <script>
        let windowWid = document.documentElement.clientWidth
        let windowHei = document.documentElement.clientHeight

        //样式1:随机出现位置的动态展示-----------------------------------
        // run()
        function Ball() {
            let ball = document.createElement('div')
            ball.setAttribute('id', 'ball')
            ball.style.opacity = 0
            ball.style.transition = 'all 1s'

            document.body.appendChild(ball)
            return ball
        }
        function run() {
            let ball = Ball()
            setInterval(() => {
                ball.style.opacity = 0

                ball = randomBall(ball)

                ball.style.opacity = 1

            }, 1000);
        }

        //样式2:弹跳动态----=============================================
        run2()
        function Ball2() {
            let ball = document.createElement('div')
            ball.setAttribute('id', 'ball')

            ball = randomBall(ball)

            document.body.appendChild(ball)
            return ball
        }
        function run2() {
            let ball = Ball2()
            let num = ball.clientWidth//这边球的宽高一样
            let x = random(-15, 15)
            let y = random(-15, 15)

            setInterval(() => {
                let left = parseInt(ball.style.left)
                if (left <= 0 || left >= (windowWid - num)) {
                    x *= -1
                }
                left += x
                ball.style.left = left + 'px'


                let top = parseInt(ball.style.top)
                if (top <= 0 || top >= (windowHei - num)) {
                    y *= -1
                }
                top += y
                ball.style.top = top + 'px'

            }, 20);
        }

        //公共部分=======================================================
        //封装随机大小 背景色 位置
        function randomBall(ball) {
            let num = random(40, 80)
            ball.style.width = num + 'px'
            ball.style.height = num + 'px'

            ball.style.backgroundColor = color(0, 255)

            ball.style.left = random(0, windowWid - num) + 'px'
            ball.style.top = random(0, windowHei - num) + 'px'
            return ball
        }
        //封装随机数
        function random(min, max) {
            //~ 按位取反   ～～执行两次，恢复成原数据，但是会变成整数
            return ~~(Math.random() * (max - min + 1) + min)
        }
        //封装随机颜色
        function color(min, max) {
            let red = random(min, max)
            let green = random(min, max)
            let blue = random(min, max)
            return `rgb(${red},${green},${blue})`
        }
    </script>
</body>

</html>